# -*- coding: utf-8 -*-
"""
配置管理模块
负责读取和管理系统各组件配置、进程数量配置等
"""

import os
import json
from typing import Dict, Any, Optional


class Config:
    """配置管理类"""
    
    def __init__(self, config_file: str = "config.json"):
        """
        初始化配置管理器
        
        Args:
            config_file: 配置文件路径
        """
        self.config_file = config_file
        self.config = self._load_config()
    
    def _load_config(self) -> Dict[str, Any]:
        """
        加载配置文件
        
        Returns:
            配置字典
        """
        if os.path.exists(self.config_file):
            with open(self.config_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        else:
            return self._get_default_config()
    
    def _get_default_config(self) -> Dict[str, Any]:
        """
        获取默认配置
        
        Returns:
            默认配置字典
        """
        return {
            # 进程配置
            "processes": {
                "log_access": 2,      # 日志接入进程数
                "log_preprocess": 3,  # 预处理进程数
                "log_analyze": 2,     # 分析引擎进程数
                "alarm_push": 1       # 告警推送进程数
            },
            
            # Elasticsearch配置
            "elasticsearch": {
                "hosts": ["localhost:9200"],
                "index_pattern": "logs-*",
                "batch_size": 1000,
                "scroll_timeout": "5m"
            },
            
            # Redis配置
            "redis": {
                "host": "localhost",
                "port": 6379,
                "db": 0,
                "password": None,
                "queue_name": "log_queue"
            },
            
            # MySQL配置
            "mysql": {
                "host": "localhost",
                "port": 3306,
                "user": "root",
                "password": "password",
                "database": "log_analysis",
                "charset": "utf8mb4"
            },
            
            # LLM配置
            "llm": {
                "api_url": "http://localhost:8000/v1/chat/completions",
                "model": "qwen2.5-7b-instruct",
                "max_tokens": 2048,
                "temperature": 0.1,
                "timeout": 30
            },
            
            # 告警配置
            "alarm": {
                "check_interval": 60,  # 告警检查间隔（秒）
                "retry_times": 3,      # 重试次数
                "retry_interval": 10   # 重试间隔（秒）
            },
            
            # Web服务配置
            "web": {
                "host": "0.0.0.0",
                "port": 5000,
                "debug": False
            },
            
            # 日志配置
            "logging": {
                "level": "INFO",
                "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                "file": "logs/app.log",
                "max_size": 100 * 1024 * 1024,  # 100MB
                "backup_count": 5
            }
        }
    
    def get(self, key: str, default: Any = None) -> Any:
        """
        获取配置值
        
        Args:
            key: 配置键，支持点号分隔的嵌套键
            default: 默认值
            
        Returns:
            配置值
        """
        keys = key.split('.')
        value = self.config
        
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        
        return value
    
    def set(self, key: str, value: Any) -> None:
        """
        设置配置值
        
        Args:
            key: 配置键，支持点号分隔的嵌套键
            value: 配置值
        """
        keys = key.split('.')
        config = self.config
        
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        
        config[keys[-1]] = value
    
    def save(self) -> None:
        """保存配置到文件"""
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(self.config, f, indent=2, ensure_ascii=False)
    
    def reload(self) -> None:
        """重新加载配置"""
        self.config = self._load_config()


# 全局配置实例
config = Config() 